package backend.event.listener;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.apache.log4j.Logger;

import backend.DefaultConf;
import backend.event.TaskInBoundEvent;
import backend.event.handler.TaskInBoundHandler;
import backend.task.FileTask;
import backend.task.TaskContext;
import backend.util.ExFileUtil;

//@SpringBean
public class TaskDiskReader extends AbstractEventListener {
	
	private static final String DEFAULT_DEMI = " ";
	private static Logger logger = Logger.getLogger(TaskDiskReader.class.getName());
	
	public Object init() throws IOException {
		
		Object result = null;
		
		File file = new File(DefaultConf.dumpTaskFile);
			if (!file.exists()) {
				if (!file.createNewFile())
					logger.error("System failed to create dump file!");
			}
		BufferedReader reader = new BufferedReader(new FileReader(file));
		String tmp = "";
		while (null != (tmp = reader.readLine())) {
			String[] tokens = tmp.split(DEFAULT_DEMI);
			FileTask task = new FileTask();
			if (tokens.length ==3) {
				File f = new File(tokens[1]);
				task.setStatus(Integer.parseInt(tokens[0]));
				task.setFile(f);
				task.setLastReadLine(Long.parseLong(tokens[2]));
				
				if(!f.exists()){
					TaskContext.removeTask(file.getAbsolutePath());
					continue;
				}
				
				String suffix = ExFileUtil.getFileSuffix(f);
				if("wk".equals(suffix)){
					//Propagate "wk" task to FileSniffer
					ExFileUtil.appendSpace(f);
					File targetFile = new File(f.getAbsolutePath()+".ok");
					if(f.renameTo(targetFile)){
						TaskContext.removeTask(file.getAbsolutePath());
					}
				}
				else if("ok".equals(suffix)){
					//We can simply inform subscribers here or propagate task to FileSniffer but may stall the
					//system initialization progress.
					
					logger.warn("Finish unfinishes :  " +  f  + "last remembered line :"+task.getLastReadLine());
				    task.setStatus(1);
				    TaskContext.putTask(task.getFile().getAbsolutePath(), task);
					TaskInBoundEvent e = new TaskInBoundEvent();
					e.setFileTask(task);
					e.addEventHandler(TaskInBoundHandler.getSpringHandler());
					this.fireEvent(e);
				}
				
			} else
				continue;
			
			TaskContext.putTask(tokens[0], task);
		}
		reader.close();
		result =  new Object();
		return result;
	}	



}
